const { AuditLog } = require('../models');

const auditLogger = (action, resourceType) => {
  return async (req, res, next) => {
    // 保存原始的 json 方法
    const originalJson = res.json;
    
    // 重写 json 方法来捕获响应
    res.json = function(data) {
      // 只在成功响应时记录审计日志
      if (res.statusCode >= 200 && res.statusCode < 300) {
        recordAuditLog(req, action, resourceType, data)
          .catch(error => console.error('Audit log error:', error));
      }
      
      // 调用原始的 json 方法
      return originalJson.call(this, data);
    };
    
    next();
  };
};

const recordAuditLog = async (req, action, resourceType, responseData) => {
  try {
    const logData = {
      userId: req.user?._id,
      action,
      resourceType,
      resourceId: req.params.id || responseData?.data?._id,
      details: {
        before: req.auditBefore || null,
        after: responseData?.data || null,
        changes: req.auditChanges || []
      },
      ip: req.ip || req.connection.remoteAddress,
      userAgent: req.get('User-Agent'),
      context: {
        projectId: req.params.projectId || req.body.projectId,
        sessionId: req.sessionID,
        requestId: req.id
      }
    };

    await AuditLog.create(logData);
  } catch (error) {
    console.error('Failed to create audit log:', error);
  }
};

// 中间件：保存操作前的数据（用于update操作）
const saveBefore = (Model) => {
  return async (req, res, next) => {
    if (req.params.id) {
      try {
        const before = await Model.findById(req.params.id);
        req.auditBefore = before?.toObject();
      } catch (error) {
        console.error('Failed to save before state:', error);
      }
    }
    next();
  };
};

module.exports = { auditLogger, saveBefore };